package com.fromcloudtocloud.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author stevejson
 */
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {
    public static List<Channel> channelList = new ArrayList<Channel>();

    /**
     * 通道读取
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //消息转发
        Channel channel = channelHandlerContext.channel();
        for (Channel ch : channelList) {
            if(ch.equals(channel)){
                continue;
            }
            ch.writeAndFlush("["+channel.remoteAddress().toString().substring(1)+"]说："+s);
        }

    }

    /**
     * 通道就绪时间
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelList.add(channel);
        System.out.println("[server]"+ channel.remoteAddress().toString()+"上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelList.remove(channel);
        System.out.println("[server]"+ channel.remoteAddress().toString()+"下线");

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        channelList.remove(channel);
        System.out.println("[server]"+ channel.remoteAddress().toString()+"异常");
    }

}
